/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#ifndef INCLUDE_SHADER_RAYTRACING
#define INCLUDE_SHADER_RAYTRACING





#ifdef __cplusplus


#else



struct S_HitInfo {
	vec3 worldPosition;
	vec3 worldNormal;
};

S_HitInfo f_glsl_getObjectHitInfo(rayQueryEXT rayQuery) {
	//const uint instanceID = rayQueryGetIntersectionInstanceIdEXT(rayQuery, true);
	const uint instanceID = rayQueryGetIntersectionInstanceCustomIndexEXT(rayQuery, true);
	const uint GeometryIndex = uint(m_ObInstance.gRtOb[instanceID].m_AddressMesh);

	// Get the ID of the triangle
	const int primitiveID = rayQueryGetIntersectionPrimitiveIndexEXT(rayQuery, true);
	const mat4x3 transform = rayQueryGetIntersectionObjectToWorldEXT(rayQuery, true);

	S_ObMesh    Resource_ObMesh = m_Mesh[GeometryIndex];
	B_Indexs    mesh_index = B_Indexs(Resource_ObMesh.m_AddressIndex);
	B_Vertices  mesh_vert = B_Vertices(Resource_ObMesh.m_AddressVertex);


	S_HitInfo result;


	// Get the indices of the vertices of the triangle
	const uvec3 index = mesh_index.I[primitiveID];

	// Get the vertices of the triangle
	const vec3 v0 = mesh_vert.V[index.x].vert;
	const vec3 v1 = mesh_vert.V[index.y].vert;
	const vec3 v2 = mesh_vert.V[index.z].vert;

	// Get the barycentric coordinates of the intersection
	vec3 barycentrics = vec3(0.0, rayQueryGetIntersectionBarycentricsEXT(rayQuery, true));
	barycentrics.x = 1.0 - barycentrics.y - barycentrics.z;

	// Compute the coordinates of the intersection
	//const vec3 objectPos = v0 * barycentrics.x + v1 * barycentrics.y + v2 * barycentrics.z;
	// For the main tutorial, object space is the same as world space:
	//result.worldPosition = objectPos;

	result.worldNormal = mat3(transform) * normalize(cross(v1 - v0, v2 - v0));
	result.worldPosition = v1;
	return result;
}


#endif





#endif //INCLUDE_SHADER_RAYTRACING



